import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { Constant, ServiceResult } from '../../../../core/constant';
import { plopService } from '../../../../service/plop/plop.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import {insService} from "../../../../service/ins/ins.service";
import {ProductService} from "../../../../service/prod/product.service";

@Component({
  selector: 'plop-view-edit',
  templateUrl: './plop-edit.component.html',
  styleUrls: ['./plop-edit.component.less']
})
export class plopViewEditComponent implements OnInit, OnDestroy {
  product:  any = {
    id:null,
    bpmStatus:null,
    orderNo:null,
    cusName:null,
    cusMobile:null,
    overduePeriod:null,
    overdueAmount:null,
    penaltyAmount:null,
    overdueUser:null,
    overdueContent:null,
    overdueRemark:null
  };

  producto:  any = {
    id:null,
    proNo: null,
    orderNo:null,
    bpmStatus:null,
    cusName: null,
    cusMobile: null,
    cusrIdtype: null,
    cusIncard: null /*No show*/,
    cusIdValidfrom: null /*No show*/,
    cusIdValidto: null /*No show*/,
    cusResAddr: null,
    cusGender: null,
    cusMaritalStatus: null /*No show*/,
    cusDeu: null /*No show*/,
    cusEthnical: null,
    cusAge: null,
    cusBirthday: null,
    cusQqid: null /*No show*/,
    cusRemark: null,
    dypname: null,
    dypvalue: null,
    dypyear: null,
    dyptype: null,
    dypclass: null,

    dypremark1: null,
    dypremark2: null,
    dypremark3: null,
    emergencyRelation:  null,
    emergencyContact: null,
    emergencyMobile: null,
    emergencyOffice:null,
    emergencyResAddr:null,
  };
  bpmStatus =  [{text: '未处理', value: '1'}, {text: '已处理', value: '10'}];
  plo_mes = [];
  MAX_COUNT = 60;
  tabIndex = 0;
  saleing = false;
  private sub: any;
  avatarParam5 = { sbtype: 'No',  filetype:'jj',orderNo: 'no'};
  uploadUr5 = '';
  proNos = [];
  cusrIdtypes = [];
  cusGenders = [];
  cusMaritalStatuss = [];
  cusDeus = [];
  cusEthnicals = [];
  dyptypes = [];
  dypclasss = [];
  relTypes=[];
  fileList = [ ];
  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;
  constructor(
    private productService: ProductService,
    public setting: SettingsService,
    private msg: NzMessageService,
    private modalService: NzModalService,
    private plopService: plopService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private cnt: Constant,
    private router: Router,
    private comm: CommService
  ) {}

   ngOnInit(): void {
   this.loadplo_mes();
    // this.loadbpmStatus();
     this.loadproNos();
     this.loadcusrIdtypes();
     this.loadcusGenders();
     this.loadcusMaritalStatuss();
     this.loadcusDeus();
     this.loadcusEthnicals();
     this.loadbpmStatus();
     this.loaddyptypes();
     this.loaddypclasss();
     this.loadrelTypes();

    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.product.id = params["id"]
      console.log("this.product.id****************"+this.product.id);
      // 获取商品详情
      this.getProductInfo();
    });
    // 隐藏reusetab
    setTimeout(() => {
      this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 100);
    this.titleService.setTitle("编辑产品")
  }
  // 加载处理类型
  loadplo_mes() {
    this.plo_mes = [];
    this.comm.getType("plo_me").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.plo_mes.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }

  loadrelTypes() {
    this.relTypes = [];
    this.comm.getType("reltype").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.relTypes.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
// 加载产品
  loadproNos() {
    this.proNos = [];
    this.comm.getType("proNo").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.proNos.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }

  // 加载证件类型
  loadcusrIdtypes() {
    this.cusrIdtypes = [];
    this.comm.getType("idType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.cusrIdtypes.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }

  // 加载性别
  loadcusGenders() {
    this.cusGenders = [];
    this.comm.getType("sex").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.cusGenders.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }

  // 加载婚姻
  loadcusMaritalStatuss() {
    this.cusMaritalStatuss = [];
    this.comm.getType("marType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.cusMaritalStatuss.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }

  // 加载学历
  loadcusDeus() {
    this.cusDeus = [];
    this.comm.getType("eduType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.cusDeus.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
//加载民族
  loadcusEthnicals() {
    this.cusEthnicals = [];
    this.comm.getType("ethType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.cusEthnicals.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  // 加载证件类型
  loadbpmStatus() {
    this.bpmStatus = [];
    this.comm.getType("bpm_status").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.bpmStatus.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  // 加载证件类型
  loaddyptypes() {
    this.dyptypes = [];
    this.comm.getType("dyptype").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.dyptypes.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  loaddypclasss() {
    this.dypclasss = [];
    this.comm.getType("dypclass").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.dypclasss.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }

  // 显示reusetab
  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  changeTab(index) {
    // 使用异步的方式更新组件, 防止ngIf错误
    Promise.resolve(null).then(() => this.tabIndex = index);
  }
  getProductInfo() {
    this.plopService.getProduct(this.product.id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.product = data.data;
      this.getProductInfoorder();
    })
  }




  getProductInfoorder() {
    this.productService.getProduct(this.product.orderNo).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      console.log("*************************"+JSON.stringify(data.data));
      this.producto = data.data;

      this.avatarParam5 = { sbtype: 'No',  filetype:'jj',orderNo: this.producto.orderNo};
      if (data.data.fxjOrderEmerList.length > 0) {
        this.producto.emergencyRelation = data.data.fxjOrderEmerList[0].emergencyRelation;
        this.producto.emergencyContact = data.data.fxjOrderEmerList[0].emergencyContact;
        this.producto.emergencyMobile = data.data.fxjOrderEmerList[0].emergencyMobile;
        this.producto.emergencyOffice = data.data.fxjOrderEmerList[0].emergencyOffice;
        this.producto.emergencyResAddr = data.data.fxjOrderEmerList[0].emergencyResAddr;
      }
      console.log("data.data.fxjOrderEmerList[0].emergencyRelation"+data.data.fxjOrderEmerList[0].emergencyRelation);
      if (data.data.fxjOrderLoanList.length > 0) {
        let flag = 0;
        for (const detail of data.data.fxjOrderLoanList) {
          console.log("detail"+detail);

          if(detail.elementNo=='10'){
            this.producto.dypname =detail.elementContent;
          }
          if(detail.elementNo=='20'){
            this.producto.dypvalue =detail.elementContent;

          }
          if(detail.elementNo=='30'){
            this.producto.dypyear =detail.elementContent;

          }
          if(detail.elementNo=='40'){
            this.producto.dyptype =detail.elementContent;

          }if(detail.elementNo=='50'){
            this.producto.dypclass =detail.elementContent;

          }
          if(detail.elementNo=='60'){
            this.producto.dypremark1 =detail.elementContent;

          }if(detail.elementNo=='70'){
            this.producto.dypremark2 =detail.elementContent;

          }if(detail.elementNo=='80'){
            this.producto.dypremark3 =detail.elementContent;
          }
        }
      };

      if (data.data.fxjOrderAttaList.length > 0) {
        let flag = 0;
        for (const detail of data.data.fxjOrderAttaList) {
          this.fileList.push( {
            uid: flag,
            name: detail.attaName,
            status: 'done',
            url: detail.attaUrl
          } )
          flag++;
        }
      };
    })
  }




  back() {
    this.router.navigate(['/prod/product/80']);
  }


  save() {


    let fxjPlOveroper = {
      updateBy:this.setting.user.username,
      id:this.product.id,
      bpmStatus:this.product.bpmStatus,
      orderNo: this.product.orderNo,
      cusName: this.product.cusName,
      cusMobile: this.product.cusMobile,
      // cusrIdtype: this.product.cusrIdtype,
      // cusIncard: this.product.cusIncard /*No show*/,
      overduePeriod: this.product.overduePeriod /*No show*/,
      // cusIdValidto: this.product.cusIdValidto /*No show*/,
      overdueAmount: this.product.overdueAmount,
      penaltyAmount: this.product.penaltyAmount,
      overdueUser:this.setting.user.username,
      overdueContent:this.product.overdueContent,
      overdueRemark:this.product.overdueRemark
    };


    // 调用接口
    this.plopService.editPro(fxjPlOveroper).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      if (data.ok === true) {
        this.msg.success('修改成功');
        this.emit.sendMessage("RELOAD_GOODS_LIST");
      } else {
        this.msg.error(data['message']);
      }
    })
  }
  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }
  changeColor(res) {
    this.product.colorSort = res.color.hex;
  }
}
